//
//  XMPhoneLoginViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/21.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMPhoneLoginViewController.h"
#import "YHCountDownButton.h"
#import "XMRegistOneViewController.h"

@interface XMPhoneLoginViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet YHCountDownButton *countDownButton;
@property (weak, nonatomic) IBOutlet UIButton *agreeButton;
@end

@implementation XMPhoneLoginViewController

- (void)rightAction {
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
#ifdef DEBUG
    self.phoneField.text = @"18888888888";
    self.codeField.text = @"888888";
#else
#endif
    [self.navRightBtn setTitle:@"遇到问题" forState:UIControlStateNormal];
    [self.navRightBtn setTitleColor:kAppMainColor forState:UIControlStateNormal];
    [self.navRightBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.phoneField.delegate = self;
    self.codeField.delegate = self;
    kCornerRadius(_loginButton, 21, 0, UIColor.clearColor);
    
    [_agreeButton setImagePosition:XMImagePositionLeft spacing:2];
    
    self.agreeButton.selected = YES;
    
    [self.phoneField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.codeField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    XMWeakSelf(self);
    [self.countDownButton countDownButtonHandler:^(YHCountDownButton *countDownButton, NSInteger tag) {
        XMStrongSelf(self);
        if ([XMUtil isBlankString:self.phoneField.text]) {
            [MBProgressHUD showHUDMsg:self.phoneField.placeholder toView:nil];
            return;
        }
        [self.phoneField resignFirstResponder];
        [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
        [[YHNetworkManager sharedInstance] postWithUrl:@"api/auth/sendMobileCode" parameters:@{@"mobile": self.phoneField.text, @"code_type": @"login"}.mutableCopy completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showHUDSucc:tip.message toView:nil];
                countDownButton.enabled = NO;
                [countDownButton startCountDownWithSecond:60];
                [countDownButton countDownChanging:^NSString *(YHCountDownButton *countDownButton, NSUInteger second) {
                    NSString *title = [NSString stringWithFormat:@"%zds", second];
                    return title;
                }];
                [countDownButton countDownFinished:^NSString *(YHCountDownButton *countDownButton, NSUInteger second) {
                    countDownButton.enabled = YES;
                    return @"重新获取";
                }];
                
            }
        }];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}

- (IBAction)agreementAct:(UIButton *)sender {
    XMWebViewController *vc = [[XMWebViewController alloc] init];
    vc.titleStr = @"用户协议";
    vc.urlStr = kGlobalVariables.appConfig.privacy.serviceAgreement;
    vc.needNav = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)privacyAct:(UIButton *)sender {
    XMWebViewController *vc = [[XMWebViewController alloc] init];
    vc.titleStr = @"隐私政策";
    vc.urlStr = kGlobalVariables.appConfig.privacy.privacyAgreement;
    vc.needNav = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)loginAct:(UIButton *)sender {
    if ([XMUtil isBlankString:_phoneField.text]) {
        [MBProgressHUD showHUDMsg:_phoneField.placeholder toView:nil];
        return;
    }
    if ([XMUtil isBlankString:_codeField.text]) {
        [MBProgressHUD showHUDMsg:_codeField.placeholder toView:nil];
        return;
    }
    
    NSMutableDictionary *dic = @{
        @"code_type": @"login",
        @"mobile": self.phoneField.text,
        @"captcha": self.codeField.text,
        @"idfa": [NSString xm_stringNoNullWith:[kMMKV getStringForKey:@"idfa"]]
    }.mutableCopy;
    
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    [YHNetworkManager.sharedInstance postWithUrl:@"api/auth/mobileLogin" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            if (![XMUtil isBlankString:kValueToString([result safe_objectForKey:@"person_id"])]) {
                NSString *person_id = kValueToString([result safe_objectForKey:@"person_id"]);
                NSString *content = [result toString:@"content"];
                if ([XMUtil isBlankString:content]) {
                    XMUserModel *model = [XMUserModel mj_objectWithKeyValues:result];
                    [XMLoginManager.sharedInstance doLoginResult:model];
                } else {
                    XMRegistOneViewController *vc = [[XMRegistOneViewController alloc] initWithNibName:kStringFromClass(XMRegistOneViewController) bundle:nil];
                    vc.person_id = person_id;
                    vc.content = content;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
            
        }
    }];
}

- (IBAction)agreeAct:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (void)textFieldDidChange:(UITextField *)textField {
    if (textField == self.phoneField) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringWithRange:NSMakeRange(0, 11)];
        }
    }
    if (textField == self.codeField) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringWithRange:NSMakeRange(0, 6)];
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    return [textField resignFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
